from decimal import Decimal
from pathlib import Path
import sys

from PySide6.QtCore import Qt, QTimer, Signal, QDate
from PySide6.QtGui import QPixmap, QFont
from PySide6.QtWidgets import QApplication, QMainWindow, QWidget, QHBoxLayout, QLabel, QSizePolicy, QTreeWidgetItem, \
    QListWidgetItem, QStackedWidget, QMessageBox, QInputDialog, QTableView, QListWidget, QHeaderView, QTableWidgetItem, \
    QDialog, QLineEdit

from backend.db.database import SessionLocal
from backend.services.certificate_services import CertificateServices
from backend.services.consumption_services import ConsumptionService
from backend.services.members_service import MemberService
from front.models.member_list_model import ConsumptionButtonDelegate
from front.ui.ui_consump_dialog import Ui_Dialog
from front.ui.ui_member_management import Ui_MainWindow
from front.ui.ui_test123 import Ui_Form
from front.ui_logic.certificates_list import CertificatesList
from front.ui_logic.consump_list import ConsumptionList
from front.ui_logic.creat_certificate import CreatCertificate
from front.ui_logic.export_excel import ExportExcel
from front.ui_logic.register import Register
from front.ui_logic.vip_list import VipList


class MemberManagement(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.add_window = None  # 添加会员对话框
        self.setupUi(self)
        self.consumption_dialog = None  # 添加对话框
        self.initialize_page()

    def initialize_page(self):
        """初始化"""
        self.add_ListWidget_item()
        self.set_ListWidget()
        self.add_stacked_widget()
        self.navigationListWidget.currentRowChanged.connect(self.list_widget_with_stack_widget)
        self.set_all_labels()
        self.vip_list_to_tableview()
        self.searchButton.clicked.connect(self.get_member_information)

    # 自动更新数据

    def need_auto_update(self):
        """自动刷新时间"""
        self.consumption_to_tableview()
        self.set_all_labels()
        self.vip_list_to_tableview()
        self.set_certificate_tableview()

    def pushButton_auto_update(self):
        """按钮刷新时间"""
        pass

    ####################################
    # 设置stackwidget和listwidget
    def set_ListWidget(self):
        """设置list_widget"""
        self.navigationListWidget.setFocusPolicy(Qt.FocusPolicy.NoFocus)
        self.navigationListWidget.setStyleSheet("""
        QListWidget::item { 
        padding: 8px; 
        border-bottom: 1px solid #e0e0e0; 
        color:#212121;
        height: 30px;  /* 所有项统一高度 */
        font:500 13px
    }
        QListWidget::item:selected {
                background: #b6e3fc;
               }
        """)

    def add_ListWidget_item(self):
        """设置list_widget选项"""

        class CenteredItemWidget(QWidget, Ui_Form):

            def __init__(self, text_data, image_path=None, parent=None):
                super().__init__(parent)
                self.setupUi(self)
                self.text_data = text_data
                self.image_path = image_path
                self.set_image_text()

            def set_image_text(self):
                if self.image_path:
                    pixmap = QPixmap(self.image_path).scaled(24, 24, Qt.KeepAspectRatio, Qt.SmoothTransformation)
                    self.label.setPixmap(pixmap)
                self.label_2.setText(self.text_data)
                self.horizontalLayout.addStretch()

        current_script = Path(__file__).resolve()
        image_file = current_script
        for i in range(3):
            image_file = image_file.parent
        items = [('会员列表', image_file / '会员.svg'), ('消费记录', image_file / '消费明细单.svg'),
                 ('存单页面', image_file / '存单发行.svg'), ('文档导出', image_file / '系统设置.svg')]
        # ('文档导出', image_file / '系统设置.svg'), ]
        for text, image in items:
            item = QListWidgetItem()
            # item.setSizeHint(CenteredItemWidget('').sizeHint())  # 设置项高度
            self.navigationListWidget.addItem(item)
            custom_widget = CenteredItemWidget(text, image, self)
            self.navigationListWidget.setItemWidget(item, custom_widget)
            flags = Qt.ItemIsSelectable | Qt.ItemIsEnabled
            item.setFlags(flags)

    def add_stacked_widget(self):
        """添加页面到stackWidget"""
        self.vip_list_page = VipList(parent=self)
        self.stackedWidget.insertWidget(0, self.vip_list_page)
        self.consumption_list_page = ConsumptionList(parent=self)
        self.stackedWidget.insertWidget(1, self.consumption_list_page)
        self.certificates_page = CertificatesList(parent=self)
        self.stackedWidget.insertWidget(2, self.certificates_page)
        self.export_excel_page = ExportExcel(parent=self)
        self.stackedWidget.insertWidget(3, self.export_excel_page)
        self.navigationListWidget.setCurrentRow(0)
        self.stackedWidget.setCurrentIndex(0)

    def list_widget_with_stack_widget(self, row):
        """联动listWidget和stackWidget"""
        self.stackedWidget.setCurrentIndex(row)
        if self.stackedWidget.currentIndex() == 0:
            self.vip_list_to_tableview()
        elif self.stackedWidget.currentIndex() == 1:
            self.consumption_to_tableview()
        elif self.stackedWidget.currentIndex() == 2:
            self.set_certificate_tableview()

    #####################################

    # 设置member的tableview
    def vip_list_to_tableview(self, data=None):
        """填充内容-tableview"""
        value_data = self.searchLineEdit.text()
        with SessionLocal() as session:
            member_service = MemberService(session)
            data = member_service.all_get_members(value_data)
            self.vip_list_page.set_table_view(data)

    # 设置consumption的tableview
    def consumption_to_tableview(self):
        """填充consumption到table_view,不包含时间"""
        with SessionLocal() as session:
            value_data = self.searchLineEdit.text()
            consumption_service = ConsumptionService(session)
            consumption_item = consumption_service.all_get_consumptions(keyword=value_data)
            self.consumption_list_page.set_table_view(consumption_item)

    # 设置存单的tableview
    def set_certificate_tableview(self):
        with SessionLocal() as session:
            value_data = self.searchLineEdit.text()
            certificate_service = CertificateServices(session)
            a = certificate_service.get_certificates(value_data)
            self.certificates_page.set_table_view(a)

    # 切换页面刷新数据,点击搜索
    def get_member_information(self):
        data = self.searchLineEdit.text()
        if self.stackedWidget.currentIndex() == 0:
            self.vip_list_page.get_member_information(data)
        elif self.stackedWidget.currentIndex() == 1:
            self.consumption_list_page.search_consumption_information(value=data)
        elif self.stackedWidget.currentIndex() == 2:
            self.certificates_page.search_certificates_information(data)

    #############################

    def set_all_labels(self):
        """设置3个Label"""
        with SessionLocal() as session:
            member_service = MemberService(session)
            all_list = member_service.get_statistics()
            self.card1Number.setText(str(all_list.total_members))
            self.card2Number.setText(str(all_list.active_members))
            self.card3Number.setText(str(all_list.today_registrations))
            self.card4Number.setText(str(all_list.today_consumption))


if __name__ == '__main__':
    app = QApplication([])
    window = MemberManagement()
    window.show()
    sys.exit(app.exec())
